/***************************************************************** 
 * temp_controll.c
 *
 * Author: Benedikt Niedermayr  <benbrenson@gmx.de>
 *
 * Description: This file contains the basic functions to arrange
 * a communication with an temperature system.
 *
 */


#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <string.h>
#include <time.h> 

#include "hardware.h"
#include "temp_controll.h"



 

/**
 * sys_controll_step - This function takes values from all
 * connected sensors and controlls dependent from the values
 * the output. Logging is also performed by this function. 
 * @terr_p: gets an system object 
 *
 */
 
int sys_controll_step (struct terra *terr_p) {

	int i,a,c;
	int ret;
	
	
	/* Get all sensor values and save them */
	terr_p->sensor_p = terr_p->sensor_pf; 
	c = FIRST_SENSOR;
	while(c <= LAST_SENSOR){
	
	terr_p->sensor_p->cur_val = terr_p->sensor_p->get_val(terr_p->sensor_p->num) ;
#ifdef DEBUG
	printf("In 'function sys_controll_step:' Value from sensor '%s' copied\n", terr_p->sensor_p->location) ;
	printf("--->%d\n",terr_p->sensor_p->cur_val) ;	
#endif	
	terr_p->sensor_p++ ;	
	c++ ;
	}


	/* Save all values to log files */
	ret = log_write(terr_p);
	
	

	/* set output values */
	ret = calculate_outputs(terr_p);
	
    /*  */
	return ret;
}


void parse_opts(int argc, char **argv)
{	
	int c;

	while((c = getopt(argc,argv,"hcwsm")) != -1)
	{
		switch(c)
		{
			case 'h' : hflag         = 1;                      break;				/* help */
			case 'c' : control_flag  = 1;                      break;
			case 'w' : wake_flag     = 1;                      break;
			case 's' : shutdown_flag = 1;                      break;
            case 'm' : create_flag   = 1;                      break;
			default : hflag    = 1;
		
			
		}

	}
	if (hflag)
	{
		printf("Usage: %s []\n", argv[0]);		
		puts("  -h               Show this page                   \n"
			 "  -c               Run control-step                 \n"
             "  -w               Weakup the System                \n"
			 "  -s               Shutdown the System              \n"
             "  -m               Create a Config file with        \n"
             "                   spezified hardware               \n"
	    
		     "\n");
	exit(1);
		
	}
}


/**
 * main only temporary for test
 *
 */ 
 
int main (int argc, char **argv)
{
	int i;
	char *str;	

	

	parse_opts(argc,argv);

	
	init_time_table(&terra1);
	printf("Time: Year=%d, Month=%d, Dayom=%d, Hour=%d, Minute=%d\n",(int) tmnow->tm_year,(int) tmnow->tm_mon,(int) tmnow->tm_mday,(int) tmnow->tm_hour,(int) tmnow->tm_min);

	if(control_flag)
	{
		/* System Initialize */
		sys_init(&terra1);
		//sys_init(&terra2);

		/* check sensor values and controll output */ 
 		sys_controll_step(&terra1);	
		//sys_controll_step(&terra2);

		/* check the critical values */	
		check_crit(&terra1);
		//check_crit(&terra2);
	}
	else if(wake_flag)
	{
		
		/* First of all wake up the system */
		weakeup(&terra1);

		/* ...And then system Initialize */
		sys_init(&terra1);
		//sys_init(&terra2);
		
	}
	else if(shutdown_flag)
	{
		/* System Initialize */
		sys_init(&terra1);
		//sys_init(&terra2);
		shutdown(&terra1);
		
	}
	else if(create_flag)
	{
		create_new_config_file(&terra1);
	}



	return 0;
}








/* Log file write */

int log_write(struct terra *terr_p)
{
	FILE *fd_log,fd_conf;
	char logfile_path[BUFF_SIZE];																
	int i;
	 
	
	/**
	 * get the correct log data which 
	 * will be written into corresponding logfile, for next sensor
     */	
	terr_p->sensor_p = terr_p->sensor_pf;
	i=FIRST_SENSOR;

	while(i <= LAST_SENSOR){
	
		/* create string for the logfile_path */	
		clearstring(&logfile_path[0]);
		strcpy(logfile_path,logfile_path_base);
		strncat(logfile_path,terr_p->sensor_p->location, BUFF_SIZE);  /* For now: The name of logfile is location of the sensor */

		if((fd_log = fopen(logfile_path, "a+")) == NULL )
		{
		 	printf("Error while opening file %s", logfile_path);
			return __ERRLOG;
		}	
			time(&t);
			/* Write current sensor value to logfile with specified date string (seconds since 1970 ....) */
			if((fprintf(fd_log,"20%d-%d-%d-%d-%d %d\n",(tmnow->tm_year - 100),(tmnow->tm_mon + 1),tmnow->tm_mday,tmnow->tm_hour ,tmnow->tm_min, terr_p->sensor_p->cur_val)) < 0) 
			{	
				printf("Error while writing logfile: %s",logfile_path);
				return __ERRLOG_WRITE;
			}
			fclose(fd_log);
			
			terr_p->sensor_p++;
			i++;
		}
	
	return 0;
}





/**
 * set_outputs - Calculate the output value of 
 * each output class dependend of sensor class.
 * 
 */

int calculate_outputs(struct terra *terr_p)
{
	int i,c = 0;
	int out_i = 0 , out_val = 0;
	int std_i = 0, std_val = 0;
	int heat_i = 0, heat_val = 0;
	int cold_i = 0, cold_val = 0;
	int hum_i = 0, hum_val = 0;
	int light_i = 0, light_val = 0;


	/* Output flags for each class, this triggers the correspond output! */ 
	int out_lowf = 0;
	int out_middlef = 0;
	int out_highf = 0;

	int fanf = 0;
	
	FILE *fd;
	char logfile_path[BUFF_SIZE];
	

	strcpy(logfile_path, logfile_path_base);
	sprintf(logfile_path, "%sTerra%d", logfile_path_base, terr_p->num); 

	/* Open file for average temperature values */
	if((fd = fopen(logfile_path, "a+")) == NULL )
		{
		 	printf("Error while opening file %s", logfile_path);
			return __ERRLOG;
		}	


	/* For now there are two lights(ground and sun) and one fan(in and out) */
	
	terr_p->sensor_p = terr_p->sensor_pf;
	i = FIRST_SENSOR;
	while(i <= LAST_SENSOR)
	{
		c = terr_p->sensor_p->type;
		switch(c)
		{
			case SENS_OUT:	out_i++;
							out_val += terr_p->sensor_p->cur_val;
							break;

			case SENS_STD:	std_i++;
							std_val += terr_p->sensor_p->cur_val;		
							break;

			case SENS_HEAT:	heat_i++;
							heat_val += terr_p->sensor_p->cur_val;
							break;

			case SENS_COLD:	cold_i++;
				  			cold_val += terr_p->sensor_p->cur_val;
							break;
			
			case SENS_HUMIDITY:	hum_i++;
								hum_val += terr_p->sensor_p->cur_val;
								break;

			case SENS_LIGHT:	light_i++;
								light_val += terr_p->sensor_p->cur_val;
								break;	
		}
	i++;
	terr_p->sensor_p++;
	}

	/* Now calculate the average values of each sensor class */
	out_val = out_i != 0 ? out_val / out_i : 0;
	std_val = std_i != 0 ? std_val / std_i : 0;
	heat_val = heat_i != 0 ? heat_val / heat_i : 0;
	cold_val = cold_i != 0 ? cold_val / cold_i : 0;
	hum_val = hum_i != 0 ? hum_val / hum_i : 0;
	light_val = light_i != 0 ? light_val / light_i : 0;

	
	fprintf(fd,"%d\n", std_val);
  	fclose(fd);

	/* The following calculation process is in work. 
     * For now it does not support the light sensor class.
	 * And supported output classes: out_high.
     */	
	
	/* Calculation for each output class: */
	/* Fan FLAG */
	if(((out_val > std_val) && (out_val > 15)) || ((hum_val > terr_p->humidity_s) && (out_val > 20)) || (std_val > terr_p->temp_in_av_s))
	{
		fanf = 1;
	}else{
		fanf = 0;
	}
	
	
	/* OUT HIGH FLAG */
	if((std_val < terr_p->temp_in_av_s))
	{
		out_highf = 1;
	}else if(std_val > terr_p->temp_in_av_s)
	{
		out_highf = 0;		
	}
	

	/* Now set the output values */
	terr_p->output_p = terr_p->output_pf;
	i = FIRST_OUTPUT;
	while(i <= LAST_OUTPUT)
	{
		/* Only change state if it is allowed(no crit value oversteped) */
		if(!terr_p->output_p->force_state)
		{ 		
			c = terr_p->output_p->type;
		
			/* Set output dependend of different classes */
			switch(c)
			{
				case OUT_GROUND : /* this is not implementet yet and will be handled by check_time() */ 	break;
			
				case OUT_HEAT_LOW :		terr_p->output_p->set_state(terr_p->output_p->num, out_lowf);
//#ifdef DEBUG
										printf("set ouput class %s to %d\n",terr_p->output_p->location, out_lowf); 	
//#endif			
										break;

				case OUT_HEAT_MIDDLE :	terr_p->output_p->set_state(terr_p->output_p->num, out_middlef);
//#ifdef DEBUG
										printf("set ouput class %s to %d\n",terr_p->output_p->location, out_middlef); 	
//#endif			
										break;
			
				case OUT_HEAT_HIGH :	terr_p->output_p->set_state(terr_p->output_p->num, out_highf);
//#ifdef DEBUG
										printf("set ouput class %s to %d\n",terr_p->output_p->location,out_highf); 	
//#endif
										break;

				case OUT_FAN : 			terr_p->output_p->set_state(0,fanf); 
										printf("set ouput class %s to %d\n",terr_p->output_p->location,fanf);
										break; 
			 
			}	
		}
		
		
		
		terr_p->output_p++;
		i++;
	}

	return 0;
}







/**
 * init_time_table - This function initializes the time table of
 * the system,this means it loads the data set of the current day into
 * the time struct for printing the date string into the logfile.
 * @terr_p: gets an system object.
 *
 */
/* 
struct tm {
    int tm_sec;         // seconds 
    int tm_min;         // minutes 
    int tm_hour;        // hours 
    int tm_mday;        // day of the month 
    int tm_mon;         // month 
    int tm_year;        // year 
    int tm_wday;        // day of the week 
    int tm_yday;        // day in the year 
    int tm_isdst;       // daylight saving time 
};
*/
int init_time_table(struct terra *terr_p)
{
	int i, cur_day,tmp;
	
	FILE *fd;
	
	struct tm *pointer;
	
	/* get actuall day */
	time(&t);
	tmnow = localtime(&t);
	cur_day = tmnow->tm_yday + 1;
	
	//Exit Programm because false time values destroying plooting the logfiles	
	if (tmnow->tm_year == 70)
	{
		printf("Time not syncronised. Exiting...\n");
		abort();
	}

	/* load actuall data of current day from config file */
	clearstring(&string[0]);
	if((fd = fopen("config/time_table","r")) == NULL)
		{	
			puts("ERROR OPENING FILE 'config/time_table'");
			return __ERRREAD;
		}
	for(i=0;i<cur_day - 1;i++)
	{
				
		fgets(string, BUFF_SIZE, fd);
		clearstring(&string[0]);
	}

		fgets(string, BUFF_SIZE, fd);
		//printf("%s\n",string);
		fclose(fd);	

	/* set time struct */
	free(terr_p->time_p);
	pointer = malloc(sizeof(struct tm));
	//sscanf(string,"d%d	a%d	u%d	 s%d	r%d	t%d", &pointer->day, &pointer->start_ground, &pointer->end_ground, &pointer->start_main, &pointer->end_main, &tmp);

#ifdef DEBUG	
	//printf("%d\n", pointer->day);
	//printf("%d\n", pointer->start_ground);
	//printf("%d\n", pointer->end_ground);
	//printf("%d\n", pointer->start_main);
	//printf("%d\n", pointer->end_main);
		
#endif	

	/* pointer to time_p */
	terr_p->time_p = pointer;
	
	//printf("terr_p->time_p %d\n", terr_p->time_p->day);
	return 0;
}











/**
 * load_conf_string() - Load config string from configfile
 * @ss: Contains the String to be searched for in the config file.
 */

char* load_conf_string(char *ss ,char *file)
{
	char *c;
	static char zeile[BUFF_SIZE];
	int i;
	FILE *fd;


	fd = fopen(file,"r");
	if( ( fd == NULL) )
	{
		printf("Error while opening file %s", configfile_path);
			//return __ERRLOG;
	}
	clearstring(&zeile[0]);
	while( (fgets(zeile, BUFF_SIZE, fd)) != NULL)
	{	
		/* Ignore Comment lines */
		if(zeile[0] == '#')
		{
			clearstring(&zeile[0]);
			continue;
		}
		/* String is found? */
		if(!strncmp(ss, zeile,strlen(ss)))
		{		
			
			c = strchr(zeile,'=')  + 1;
			fclose(fd);
			return c;
			
		}
		
		
	}
	
	fclose(fd);
	return c;
}

#if 0 
/**
 * change_conf_string() - change spezified config string from configfile
 * @ss: Contains the String to be searched for in the config file.
 * @cc: Contains the new value for the config string
 */
int ch_config_string(char *ss, char *cc)
{
	char *c;
	int i;
	FILE *fd;

	fd = fopen("config/terra.conf","a");
	fseek(fd, 0,SEEK_SET);
	fputs("O",fd);


}

#endif 

/**
 * shutdown() - Shutdown the whole system 
 * @terr_p: gets an system object.
 */
int shutdown(struct terra *terr_p)
{
	int i,c;
	char tmp[BUFF_SIZE];
	char x;
	FILE *fd;


	printf("shutdown called\n");
	system("rm .tmp");
	if((fd = fopen(".tmp", "a+")) == NULL )
	{
	 	printf("Error while opening temp file \n");
		return __ERRLOG;
	}
	
	terr_p->output_p = terr_p->output_pf;
	i = FIRST_OUTPUT;
	while(i <= LAST_OUTPUT)
	{
		
		terr_p->output_p->set_state(terr_p->output_p->num, 0);
		
		printf("Set output %s to 0\n",terr_p->output_p->location);
		terr_p->output_p->force_state = 1;

        fprintf(fd,"OUTPUT%i_FSTATE=%i\n", terr_p->output_p->num, terr_p->output_p->force_state);

		i++;
		terr_p->output_p++;
	}
	fclose(fd);
}





/**
 * weakeup() - Weakup the OUT_GROUND Class, other outputs should only 
 * get the no force state and will be controlled by calculate functions! 
 * @terr_p: gets an system object.
 */
int weakeup(struct terra *terr_p)
{
	int i,c;
	FILE *fd;
	char tmp[BUFF_SIZE];
	char x;

	printf("wakeup called\n");
	system("rm .tmp");

	if((fd = fopen(".tmp", "a+")) == NULL )
	{
	 	printf("Error while opening temp file \n");
		return __ERRLOG;
	}	

	terr_p->output_p = terr_p->output_pf;
	i = FIRST_OUTPUT;
	while(i <= LAST_OUTPUT)
	{
		if(terr_p->output_p->type == OUT_GROUND)
		{
			terr_p->output_p->set_state(terr_p->output_p->num, 1);
		
			printf("Set output %s to 1\n",terr_p->output_p->location);
			
		}
	
	terr_p->output_p->force_state = 0;
	fprintf(fd,"OUTPUT%i_FSTATE=%i\n", terr_p->output_p->num, terr_p->output_p->force_state);
	
	i++;
	terr_p->output_p++;	
	}
	fclose(fd);
}






/**
 * sys_init() - This function initialises the specified system
 * It reads the config file and stores all Variables into the ram
 * @terr_p: gets an system object
 */
int sys_init(struct terra *terr_p)
{
	char *day_temp, *day_hum, *tmp_standby, *test;
	char tmp[BUFF_SIZE];
	char *tmp2;
	int i,testi;

#ifdef DEBUG
	printf("[sys_init] start function\n");
#endif

	
	/* load config file to environment */
	/* DAY_TEMP *
     * loads the should temperature for specified terra */
	day_temp = load_conf_string("DAY_TEMP",configfile_path);
	terr_p->temp_in_av_s = atoi(day_temp);
	if(!terr_p->temp_in_av_s)
	{
		return __ERRCONN;
	}
#ifdef DEBUG
	printf("DAY_TEMP => %d\n",terr_p->temp_in_av_s);
#endif
	
	/*TEMP_STANDBY*/
    tmp_standby = load_conf_string("TEMP_STANDBY",configfile_path);
	terr_p->temp_standby = atoi(tmp_standby);
	if(!terr_p->temp_standby)
	{
		return __ERRCONN;
	}
#ifdef DEBUG
	printf("TEMP_STANDBY => %d\n",terr_p->temp_standby);
#endif

	/* DAY_HUM *
     * loads the should humidity for specified terra */
	day_hum = load_conf_string("DAY_HUM",configfile_path);
	terr_p->humidity_s = atoi(day_hum);
	if(!terr_p->humidity_s)
	{
		return __ERRCONN;
	}
#ifdef DEBUG
	printf("DAY_HUM => %d\n",terr_p->humidity_s);
#endif
	
	

    /* No get all Sensor Variables */ 
	terr_p->sensor_p = terr_p->sensor_pf;
	i = FIRST_SENSOR;
	while(i <= LAST_SENSOR)
	{
		/* Get location with copying the string */		
		clearstring(tmp);
		clearstring(&terr_p->sensor_p->location[0]);
		sprintf (tmp, "SENSOR%i_LOCATION", terr_p->sensor_p->num);

		strcpy(terr_p->sensor_p->location,load_conf_string(tmp, configfile_path));
		clearstring_newline(&terr_p->sensor_p->location[0]);
#ifdef DEBUG
		printf("SENSOR%i_LOCATION=%s\n", terr_p->sensor_p->num, terr_p->sensor_p->location);
#endif		
		/* Get Sensor Class */
		clearstring(tmp);
		sprintf (tmp, "SENSOR%i_SENSORCLASS", terr_p->sensor_p->num);
		terr_p->sensor_p->type = atoi(load_conf_string(tmp, configfile_path));
#ifdef DEBUG	
		printf("SENSOR%i_SENSORCLASS=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->type);
#endif
		/* Get Crit_max Value */
		clearstring(tmp);
		sprintf (tmp, "SENSOR%i_CRITMAX", terr_p->sensor_p->num);
		terr_p->sensor_p->critical_max = atoi(load_conf_string(tmp, configfile_path));	
#ifdef DEBUG
		printf("SENSOR%i_CRITMAX=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->critical_max);
#endif
		/* Get Crit_min Value */
		clearstring(tmp);
		sprintf (tmp, "SENSOR%i_CRITMIN", terr_p->sensor_p->num);
		terr_p->sensor_p->critical_min = atoi(load_conf_string(tmp, configfile_path));	
#ifdef DEBUG
		printf("SENSOR%i_CRITMIN=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->critical_min);
#endif

		i++;
		terr_p->sensor_p++;	
	}
    
	/* Now get all output variables */
	terr_p->output_p = terr_p->output_pf;
	i = FIRST_OUTPUT;
	while(i <= LAST_OUTPUT)
	{
		/* Get location with copying the string */		
		clearstring(tmp);
		clearstring(&terr_p->output_p->location[0]);
		sprintf (tmp, "OUTPUT%i_LOCATION", terr_p->output_p->num);

		strcpy(terr_p->output_p->location,load_conf_string(tmp,configfile_path));
		clearstring_newline(&terr_p->output_p->location[0]);
#ifdef DEBUG
		printf("OUTPUT%i_LOCATION=%s\n", terr_p->output_p->num, terr_p->output_p->location);
#endif
		/* Get Output Class */
		clearstring(tmp);
		sprintf (tmp, "OUTPUT%i_OUTPUTCLASS", terr_p->output_p->num);
		terr_p->output_p->type = atoi(load_conf_string(tmp, configfile_path));	
#ifdef DEBUG
		printf("OUTPUT%i_SENSORCLASS=%i\n", terr_p->output_p->num, terr_p->output_p->type);
#endif		
		/* Get Force_state */
		clearstring(tmp);
		sprintf (tmp, "OUTPUT%i_FSTATE", terr_p->output_p->num);
		terr_p->output_p->force_state = atoi(load_conf_string(tmp, tmp_file_path));
#ifdef DEBUG
		printf("OUTPUT%i_FSTATE=%i\n", terr_p->output_p->num, terr_p->output_p->force_state);
#endif
		
		i++;
		terr_p->output_p++;	
	}

#ifdef DEBUG
	printf("[sys_init] returned 0 \n");
#endif
	return 0;
}


/* create additional (dynamic) information for the connected sensors
 * of the system.
 * This function will be called with a given parameter of this program (-m) 
 * @terr_p: gets an system object
 */
int create_new_config_file(struct terra *terr_p)
{
	int i;    
	FILE *fd, *fd_tmp;
	

	if((fd = fopen(configfile_path, "w")) == NULL )
		{
		 	printf("Error while opening file %s", configfile_path);
			return __ERRLOG;
		}	
	
	if((fd_tmp = fopen(tmp_file_path, "a+")) == NULL )
		{
		 	printf("Error while opening file %s", tmp_file_path);
			return __ERRLOG;
		}	

	fputs("DAY_TEMP=30\n", fd);
	fputs("TEMP_STANDBY=20\n", fd);
	fputs("DAY_HUM=20\n", fd);
	fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);

    /* Write down following structure for each sensor

       xSENSOR%num 
       LOCATION=%location
       SENSORCLASS=%type
       CRITMAX=%critical_max
       CRITMIN=%critical_min
    */
	terr_p->sensor_p = terr_p->sensor_pf;
	i = FIRST_SENSOR;
	while(i <= LAST_SENSOR)
	{
		//fprintf(fd,"xSENSOR%i\n", terr_p->sensor_p->num);
		fprintf(fd,"SENSOR%i_LOCATION=%s\n", terr_p->sensor_p->num, terr_p->sensor_p->location);
		fprintf(fd,"SENSOR%i_SENSORCLASS=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->type);
		fprintf(fd,"SENSOR%i_CRITMAX=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->critical_max);
		fprintf(fd,"SENSOR%i_CRITMIN=%i\n", terr_p->sensor_p->num, terr_p->sensor_p->critical_min);
		fputs("\n",fd);
		
		terr_p->sensor_p++;
		i++;
	}
    fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);

    /* Write down the following information of each output
       xOUTPUT%num
       LOCATION=%location
       OUTPUTCLASS=%type
       FSTATE=%force_state
    */
	terr_p->output_p = terr_p->output_pf;
	i = FIRST_OUTPUT;
	while(i <= LAST_OUTPUT)
	{
		//fprintf(fd,"xOUTPUT%i\n", terr_p->output_p->num);
		fprintf(fd,"OUTPUT%i_LOCATION=%s\n", terr_p->output_p->num, terr_p->output_p->location);
		fprintf(fd,"OUTPUT%i_OUTPUTCLASS=%i\n", terr_p->output_p->num, terr_p->output_p->type);
		fprintf(fd_tmp,"OUTPUT%i_FSTATE=%i\n", terr_p->output_p->num, terr_p->output_p->force_state);
		fputs("\n",fd);

		i++;
		terr_p->output_p++;
	}
	
	fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);
	fputs("\n",fd);
	fclose(fd);
	fclose(fd_tmp);

	
	
	return 0;
}


/**
 * check_crit() -This function checks, wether critical
 * values have been overstepped.
 * 
 */

int check_crit(struct terra *terr_p)
{
	int i;
	FILE *fd;

	
	if((fd = fopen(errlog_path, "a+")) == NULL )
		{
		 	printf("Error while opening file %s", errlog_path);
			return __ERRLOG;
		}	
	
	terr_p->sensor_p = terr_p->sensor_pf;
	i = FIRST_SENSOR;
	while(i <= LAST_SENSOR)
	{
		if(terr_p->sensor_p->critical_max < terr_p->sensor_p->cur_val) 
		{
			fprintf(fd,"Critical maximal value (%d°C) for Sensor %s reached. Currrent temperature is %i\n", terr_p->sensor_p->critical_max, terr_p->sensor_p->location, terr_p->sensor_p->cur_val);
			 
		}
		else if(terr_p->sensor_p->critical_min > terr_p->sensor_p->cur_val)
		{
			fprintf(fd,"Critical minimal value (%d°C) for Sensor %s reached. Current temperature is %i\n", terr_p->sensor_p->critical_min, terr_p->sensor_p->location, terr_p->sensor_p->cur_val);
		}
	i++;
	terr_p->sensor_p++;
	}

fclose(fd);
}

